package org.itboys.mobile.controller.mobile;

import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.apache.commons.collections.map.HashedMap;
import org.apache.ibatis.annotations.One;
import org.itboys.commons.CommonConstants;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.kitchen.entity.mysql.income.KitchenIncome;
import org.itboys.kitchen.util.MobileSignUtils;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dto.count.KitchenCountDto;
import org.itboys.mobile.dto.score.SundayMemberFinanceDto;
import org.itboys.mobile.service.mongo.mobile.KitchenMobileCartService;
import org.itboys.mobile.service.mongo.mobile.SundayMobileMemberService;
import org.itboys.mobile.service.mysql.mobile.income.KitchenMobileIncomeService;
import org.itboys.mobile.util.AccountIdHoldUtils;
import org.itboys.mobile.util.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：jiangxiong
 * 日期：2017年2月9日
 * 联系方式 ：empty90911@126.com
 * 描述：农厨_钱包（首页）_controller。
 *
 */
@Controller
@RequestMapping("/kitchen/mobile/income")
public class KitchenMobileIncomeController extends BaseController{
    @Autowired
    private KitchenMobileIncomeService incomeService;
    @Autowired
    private SundayMobileMemberService memberService;
    /**
     * 【用户版和管理版】钱包，获取充值产品。不分页
     * @param request
     * @param response
     * @param nonce
     * @param sign
     */
    @RequestMapping(value="/getRevenue",method= RequestMethod.POST)
    @ApiOperation(value="【用户版和管理版】钱包，获取钱包余额")
    public void getRevenue(HttpServletRequest request,
                               HttpServletResponse response,
                               @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                               @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ) {
        try{
            Long memberId = AccountIdHoldUtils.getMemberId();
           // KitchenIncome income =incomeService.findOne(memberId);
            //2017年8月28日
            SundayMemberFinanceDto financeDto=memberService.getMemberFinance(memberId,null);
            Map<String,Object> result=new HashMap<String,Object>();
          /*  result.put("totalRevenue",income.getTotalRevenue());
            result.put("ableRevenue",income.getAbleRevenue());
            result.put("frozenRevenue",new BigDecimal("0"));*/
            result.put("totalRevenue",financeDto.getBalance());
            result.put("ableRevenue",financeDto.getBalance());
            result.put("frozenRevenue",new BigDecimal("0"));
            result.put("info","totalRevenue(总余额，暂不适用)，ableRevenue（可用余额），frozenRevenue（冻结余额，暂不适用）");
            ResponseMessage.success(result);
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/kitchen/mobile/income/getRevenue----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }

    /**
     * 获取交易记录
     * @param request
     * @param response
     * @param type
     * @param remark
     * @param pageSize
     * @param pageNumber
     * @param sort
     * @param order
     * @param nonce
     * @param sign
     */
    @RequestMapping(value="/record/select",method= RequestMethod.POST)
    @ApiOperation(value="【用户版和管理版】钱包（收益）获取交易记录。分页")
    public void record_select(HttpServletRequest request,
                        HttpServletResponse response,
                       // @ApiParam(required = true, name = "memberId", value = "用户ID") @RequestParam(value="memberId",required=true) Long memberId,
                        @ApiParam(required = false, name = "type", value = "查询参数。交易类型。1，充值，2，充值赠送，3，消费抵扣，4系统返还") @RequestParam(value = "type", required = false)Integer type,
                        @ApiParam(required = false, name = "remark", value = "查询参数。交易备注。") @RequestParam(value = "remark", required = false)String remark,

                        @ApiParam(required = true, name = "pageSize", value = "分页参数。每页数量。默认20") @RequestParam(value = "pageSize", required = true) String pageSize,
                        @ApiParam(required = true, name = "pageNumber", value = "分页参数。第几页。默认1") @RequestParam(value = "pageNumber", required = true) String pageNumber,
                        @ApiParam(required = false, name = "sort", value = "排序参数。字段名称。默认为空") @RequestParam(value = "sort", required = false) String sort,
                        @ApiParam(required = false, name = "order", value = "排序参数。。默认为空。ASC正序/DESC倒序") @RequestParam(value = "order", required = false) String order,
                        @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                        @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ) {
        try{
            Long memberId = AccountIdHoldUtils.getMemberId();
            List<Map<String,Object>> result =incomeService.getRecords(request,memberId);
            ResponseMessage.success(result);
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/kitchen/mobile/income/record/select----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }

    /**
     * 【用户版和管理版】钱包，获取充值产品。不分页
     * @param request
     * @param response
     * @param nonce
     * @param sign
     */
    @RequestMapping(value="/product/select",method= RequestMethod.POST)
    @ApiOperation(value="【用户版和管理版】钱包，获取充值产品。不分页")
    public void product_select(HttpServletRequest request,
                        HttpServletResponse response,
                         @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                        @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ) {
        try{
            Long memberId = AccountIdHoldUtils.getMemberId();
            List<Map<String,Object>> result =incomeService.getProducts(memberId);
            ResponseMessage.success(result);
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/kitchen/mobile/income/product/select----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }


    /**
     * 【用户版和管理版】钱包-充值-创建订单。单次只能购买一个充值产品
     * @param request
     * @param response
     * @param productId
     * @param nonce
     * @param sign
     */
    @RequestMapping(value="/product/createOrder",method= RequestMethod.POST)
    @ApiOperation(value="【用户版和管理版】钱包-充值-创建订单。单次只能购买一个充值产品")
    public void product_createOrder(HttpServletRequest request,
                               HttpServletResponse response,
                                @ApiParam(required = true, name = "productId", value = "充值产品Id") @RequestParam(value = "productId", required = true)Long productId,
                                @ApiParam(value = "随机数")@RequestParam(value = "nonce", required = true) String nonce,
                                @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign
    ) {
        try{
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("productId",productId);
            param.put("nonce", nonce);
            param.put("sign", sign);
           /* boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
                ResponseMessage.error(-1,"签名校验失败");
                return;
            }*/
            Long memberId = AccountIdHoldUtils.getMemberId();
            Map<String,Object> result =incomeService.createOrder(memberId,productId);
            ResponseMessage.success(result);
        }catch (Exception e){
            String msg =CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/kitchen/mobile/income/product/createOrder----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }











}
